package fr.uvsq.isty.bdh.hchess.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.net.URL;
import org.ini4j.Wini;

/**
 * Overrides the Wini class from ini4j to provide a getter with default value.
 * 
 * The constructors are the same as its parent class.
 * @author Clement Bellot <clementbellot@gmail.com>
 * @author Florent Hemmi <florent.hemmi@gmail.com>
 */
public class ConfigFile extends Wini {
    public ConfigFile(){
        super();
    }
    public ConfigFile(Reader r) throws IOException {
        super(r);
    }
    public ConfigFile(InputStream is) throws IOException {
        super(is);
    }
    public ConfigFile(URL l) throws IOException {
        super(l);
    }
    public ConfigFile(File f) throws IOException {
        super(f);
    }
    /**
     * See Wini documentation.
     * @param defaultValue default value if the requested entry is not found.
     * @return If the entry is not found, this will be return, and
     * the given entry will be created with this value.
     */
    public String get(Object sectionName,
            Object optionName,
            String defaultValue) {
        
        try {
            String ret = this.get(sectionName, optionName);
            if(ret == null){
                throw new IOException();
            }
            return ret;
        } catch(IOException ex){
            try {
                this.put((String)sectionName, (String)optionName, (Object)defaultValue);
                this.store();
            } catch (IOException ex1) {}
        }
        return defaultValue;
    }
    /**
     * See <code>get(Object sectionName,Object optionName,String defaultValue)
     * </code>, but with <code>int</code>s.
     * @return same as get but return an integer
     */
    public int getInt(Object sectionName,
            Object optionName,
            int defaultValue) {
        
        return Integer.parseInt(get(sectionName, optionName, String.valueOf(defaultValue)));
    }
    /**
     * See <code>get(Object sectionName,Object optionName,String defaultValue)
     * </code>, but with <code>double</code>s.
     * @return same as get but return a double
     */
    public double getDouble(Object sectionName,
            Object optionName,
            double defaultValue) {
        
        return Double.parseDouble(get(sectionName, optionName, String.valueOf(defaultValue)));
    }
}
